<?php
/**
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT		: Rubik Ultimate Framework
 * @version 	: 1.1
 * COPYRIGHT    : 2008
 * ------------------------------------------------------
 * 
 * Created on	:  Jul 15, 2008
 * 
 */

// no direct access
defined ( '_FW_EXEC' ) or die ( 'Restricted access' );

RCoreImporter::cls( "html.HtmlControl" );

class FlashUploadControl extends HtmlControl {
	
	var $_maxFileSize;
	var $_fileExtension;
	var $_process;
	
	/** Default value is FALSE (no cropping)
	 *
	 * @access public
	 * @var Boolean;
	 */
	var $image_crop;
	
	/**
	 * Set this variable to the wanted (or maximum/minimum) width for the processed image, in pixels
	 *
	 * Default value is 150
	 *
	 * @access public
	 * @var integer
	 */
	var $image_x;
	
	/**
	 * Set this variable to the wanted (or maximum/minimum) height for the processed image, in pixels
	 *
	 * Default value is 150
	 *
	 * @access public
	 * @var integer
	 */
	var $image_y;
	
	var $_createFolder;
	var $_multiImg;
	
	function __construct($fieldName, $fileExtension, $resource, $maxFileSize = 1073741824000, $bCreate = false, $bMultiImg = false) {
		$this->_maxFileSize = $maxFileSize;
		$this->_fileExtension = $fileExtension;
		$this->_process = $resource;
		$this->_inputName = $fieldName;
		$this->image_crop = false;
		$this->_createFolder = $bCreate;
		$this->_multiImg = $bMultiImg;
	}
	
	function validateExtension($file) {
		$path_info = pathinfo ( $file );
		$file_extension = $path_info ["extension"];
		$is_valid_extension = false;
		foreach ( $this->_fileExtension as $extension ) {
			if (strtolower ( $file_extension ) == $extension) {
				$is_valid_extension = true;
				break;
			}
		}
		if (! $is_valid_extension) {
			$this->handleError ( "Invalid file extension" );
			exit ( 0 );
		}
	}
	
	function validateSize($file) {
		$file_size = @filesize ( $file );
		if (! $file_size || $file_size > $this->_maxFileSize) {
			$this->handleError ( "File exceeds the maximum allowed size" );
			exit ( 0 );
		}
		
		if ($file_size <= 0) {
			$this->handleError ( "File size outside allowed lower bound" );
			exit ( 0 );
		}
	}
	
	function validateUploading($fileInfo) {
		if (! isset ( $fileInfo ["Filedata"] )) {
			$this->handleError ( "No upload found" );
			exit ( 0 );
		} else if (isset ( $fileInfo ["Filedata"] ["error"] ) && $fileInfo ["Filedata"] ["error"] != 0) {
			$this->handleError ( "Some error" );
			exit ( 0 );
		} else if (! isset ( $fileInfo ["Filedata"] ["tmp_name"] ) || ! @is_uploaded_file ( $fileInfo ["Filedata"] ["tmp_name"] )) {
			$this->handleError ( "Upload failed is_uploaded_file test." );
			exit ( 0 );
		} else if (! isset ( $fileInfo ["Filedata"] ['name'] )) {
			$this->handleError ( "File has no name." );
			exit ( 0 );
		}
	}
	
	function fileIsExit($filePath) {
		if (file_exists ( $filePath )) {
			return true;
		}
		return false;
	}
	
	function getUploadDir($folderName = '', $url = false) {
		if (! $url) {
			$DS = DS;
			$folderName = empty ( $folderName ) ? '' : $folderName . $DS;
			$rootPath = SYS_ROOT_PATH;
		} else {
			$DS = "/";
			$folderName = empty ( $folderName ) ? '' : $folderName . $DS;
			$rootPath = '';
		}
		
		$rootPath .= 'files' . $DS . $folderName;
		if ($this->_createFolder) {
			$arr [] = date ( "Y" );
			$arr [] = date ( "m" );
			$arr [] = date ( "d" );
			$arr [] = date ( "H" );
			$dir = $rootPath;
			foreach ( $arr as $value ) {
				$dir .= $value . $DS;
				if (! is_dir ( $dir ) && ! $url) {
					mkdir ( $dir );
				}
			}
			return $dir;
		}
		return $rootPath;
	}
	
	function getFileName($file) {
		$arrName = explode ( '.', $file );
		$fileBody = $arrName [0];
		$fileExt = $arrName [1];
		$rand = rand ( 2, 50 );
		$file_name = substr ( md5 ( $rand * time () ), 0, 10 );
		//		$file_name = preg_replace('/[^'.'.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-'.']|\.+$/i', "", basename($fileBody));
		$file_name = str_replace ( " ", "_", $file_name ) . '.' . $fileExt;
		return $file_name;
	}
	
	function validate($fileInfo) {
		$this->validateUploading ( $fileInfo );
		$this->validateSize ( $fileInfo ["Filedata"] ["tmp_name"] );
		$this->validateExtension ( $fileInfo ["Filedata"] ['name'] );
		return;
	}
	
	function uploadFiles($dirName = '') {
		$fileInfo = $_FILES;
		$this->validate ( $fileInfo );
		$uploadDir = $this->getUploadDir ( $dirName );
		$uploadDirUrl = $this->getUploadDir ( $dirName, true );
		$file_name = $this->getFileName ( $fileInfo ["Filedata"] ["name"] );
		if ($this->fileIsExit ( $uploadDir . $file_name ))
			$file_name = $this->autoChangeFileName ( $file_name, $uploadDir );
		if (! @move_uploaded_file ( $fileInfo ["Filedata"] ["tmp_name"], $uploadDir . $file_name )) {
			$this->handleError ( "File could not be saved." );
			exit ( 0 );
		}
		
		$file_path = SYS_ROOT_URL . $uploadDirUrl . $file_name;
		$description = $file_path;
		
		if ($this->image_crop) {
			$thumbnail = $this->createThumbnailImages ( $uploadDir . $file_name );
			$thumbnailImage = "<img src=\"" . SYS_ROOT_URL . $thumbnail . "\" />";
			$description = $thumbnailImage;
			if ($this->hasError ()) {
				$output = $this->getAllErrorsMsg ();
				echo $output;
				return $output;
			}
		}
		
		$output = "
				<table>
					<thead><tr><th>Delete</th><th>Main Images</th><th>Description</th></tr></thead>
					<tbody>
						<tr class=\"odd\">
							<td>
								<div class=\"form-item\">
									<input type=\"checkbox\" class=\"form-checkbox\" value=\"{$file_name}\" name=\"filesDelete[]\"/>
								</div>
							</td>
							<td>
								<div class=\"form-item\">
									<input type=\"radio\" value=\"{$file_name}\" name=\"imageChecked\" />
								</div>
							</td>
							<td>
								<div class=\"form-item\">
									<div class=\"description\">{$description}</div>
								</div>
					</tbody>
				</table>
			";
		$output .= "<input type=\"hidden\" name=\"{$this->_inputName}[]\" value=\"" . $uploadDirUrl . $file_name . "\" />";
		$output .= "<input type=\"hidden\" name=\"{$this->_inputName}_thumb[]\" value=\"" . $thumbnail . "\" />";
		echo $output;
		return;
	}
	
	function createThumbnailImages($filePath) {
		RCoreImporter::cls( "html.UploadFileControl" );
		$image = new UploadFileControl ( $filePath );
		
		if (! empty ( $image->error )) {
			$this->setError ( $image->error );
		}
		
		$imageSize = GetImageSize ( $filePath );
		$imageWidth = $imageSize [0];
		$imageHeght = $imageSize [1];
		
		if ($imageWidth > $imageHeght) {
			$right = $imageWidth - $imageHeght;
			$size = array (0, $right, 0, 0 );
		} else {
			$bottom = $imageHeght - $imageWidth;
			$size = array (0, 0, $bottom, 0 );
		}
		
		$image->image_resize = true;
		$image->image_crop = ($size);
		$image->image_x = $this->image_x;
		$image->image_y = $this->image_y;
		$image->process ( 'thumbnails' );
		if (! empty ( $image->error )) {
			$this->setError ( $image->error );
		}
		$dir = $image->getUploadDir ( 'thumbnails', true );
		$arrThumbnailImages = $dir . $image->file_dst_name;
		
		return $arrThumbnailImages;
	}
	
	function createInputHtml($multiFiles = true) {
		SysResponse::addJavascriptFile ( SYS_ROOT_URL . "libraries/js/swfupload.js" );
		SysResponse::addJavascriptFile ( SYS_ROOT_URL . "libraries/js/swfupload.queue.js" );
		SysResponse::addJavascriptFile ( SYS_ROOT_URL . "libraries/js/fileprogress.js" );
		SysResponse::addJavascriptFile ( SYS_ROOT_URL . "libraries/js/handlers.js" );
		$flashUrl = SYS_ROOT_URL . "libraries/js/upload.swf";
		
		$arrExt = array ();
		foreach ( $this->_fileExtension as $value ) {
			$arrExt [] = '*.' . $value;
		}
		$fileExt = implode ( ';', $arrExt );
		
		$sessionId = session_id ();
		$script = "
			var swfu;

		window.onload = function() {
			var settings = {
				flash_url : \"{$flashUrl}\",
				upload_url: \"{$this->_process}\",	// Relative to the SWF file
				post_params: {\"PHPSESSID\" : \"{$sessionId}\"},
				file_size_limit : \"{$this->_maxFileSize}\",
				file_types : \"{$fileExt}\",
				file_types_description : \"All Files\",
				file_upload_limit : 100,
				file_queue_limit : 0,
				custom_settings : {
					progressTarget : \"{$this->_inputName}_progress\",
					cancelButtonId : \"btnCancel\"
				},
				debug: false,

				// The event handler functions are defined in handlers.js
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,
				queue_complete_handler : queueComplete	// Queue plugin event
			};
			swfu = new SWFUpload(settings);
	     };
			";
		SysResponse::addJavascriptContent ( $script );
		$output = "";
		if ($multiFiles) {
			$output .= "
						<div class=\"flash\" id=\"{$this->_inputName}_progress\"></div>
						<div id=\"divStatus\"></div>
						<div>
							<input type=\"button\" value=\"Upload file\" onclick=\"swfu.selectFiles()\" style=\"font-size: 8pt;\" />
							<input id=\"btnCancel\" type=\"button\" value=\"Cancel\" onclick=\"swfu.cancelQueue();\" disabled=\"disabled\" style=\"font-size: 8pt;\" />
						</div>
			";
		} else {
			$output .= "
						<div class=\"flash\" id=\"{$this->_inputName}_progress\"></div>
						<div id=\"divStatus\" style=\"display:none\"></div>
						<div>
							<input type=\"button\" value=\"Upload file\" onclick=\"swfu.selectFile()\" style=\"font-size: 8pt;\" />
							<input style=\"display:none\" id=\"btnCancel\" type=\"button\" value=\"Cancel\" onclick=\"swfu.cancelQueue();\" disabled=\"disabled\" style=\"font-size: 8pt;\" />
						</div>
			";
		}
		return $output;
	}
	
	function printInputHtml($multiFiles = true) {
		echo $this->createInputHtml ( $multiFiles );
	}
	
	function autoChangeFileName($fileName, $fileDir) {
		$arrName = explode ( '.', $fileName );
		$fileBody = $arrName [0];
		$fileExt = $arrName [1];
		$cpt = 1;
		$name = "";
		$filePath = $fileDir . $fileName;
		
		while ( @file_exists ( $filePath ) ) {
			$fileBody = $fileBody . '_' . $cpt;
			$name = $fileBody . '.' . $fileExt;
			$cpt ++;
			$filePath = $fileDir . $name;
		}
		return $name;
	}
	
	function handleError($message) {
		//		if (!headers_sent()) {
		//			header("HTTP/1.1 500 Internal Server Error");
		//		}
		echo $message;
	}
}

?>